package com.elysia.gulimall.product.service.impl;

import com.elysia.common.constant.ProductConstant;
import com.elysia.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.elysia.gulimall.product.dao.AttrGroupDao;
import com.elysia.gulimall.product.dao.CategoryDao;
import com.elysia.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.elysia.gulimall.product.entity.AttrGroupEntity;
import com.elysia.gulimall.product.entity.CategoryEntity;
import com.elysia.gulimall.product.service.CategoryService;
import com.elysia.gulimall.product.vo.AttrGroupRelationVo;
import com.elysia.gulimall.product.vo.AttrRespVo;
import com.elysia.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.common.utils.PageUtils;
import com.elysia.common.utils.Query;

import com.elysia.gulimall.product.dao.AttrDao;
import com.elysia.gulimall.product.entity.AttrEntity;
import com.elysia.gulimall.product.service.AttrService;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void save(AttrVo attr) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        if(attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null) {
            //基本属性才需要保存关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId,String type) {
        QueryWrapper<AttrEntity> wrapper=new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
        }
        String key=(String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(obj->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils=new PageUtils(page);
        List<AttrEntity> records=page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //查category表得到 所属分类的名字
            CategoryEntity categoryEntity=categoryDao.selectById(attrRespVo.getCatelogId());
            if(categoryEntity!=null) attrRespVo.setCatelogName(categoryEntity.getName());
            //查pms_attr_attrgroup_relation表 得到所属分组的id
            if(attrRespVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                //基本属性才需要查分组
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId()));
                if(attrAttrgroupRelationEntity!=null && attrAttrgroupRelationEntity.getAttrGroupId()!=null){
                    attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                    //查attrGroup表 得到所属分组名
                    AttrGroupEntity attrGroupEntity=attrGroupDao.selectById(attrRespVo.getAttrGroupId());
                    if(attrGroupEntity!=null) attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo=new AttrRespVo();
        AttrEntity attrEntity=this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        //调用categoryService.getCategoryPathById得到分类路径
        attrRespVo.setCatelogPath(categoryService.getCategoryPathById(attrRespVo.getCatelogId()));
        //获取分组
        if(attrRespVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //基本属性才需要查分组
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
            if(attrAttrgroupRelationEntity!=null){
                attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity= attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity!=null) attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本信息
        this.updateById(attrEntity);
        //保存pms_attr_attrgroup_relation
        if(attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //基本属性才需要分组
            AttrAttrgroupRelationEntity relation=new AttrAttrgroupRelationEntity();
            relation.setAttrId(attr.getAttrId());
            relation.setAttrGroupId(attr.getAttrGroupId());
            Long count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            if (count>0){
                //修改
                attrAttrgroupRelationDao.update(relation,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else{
                //新增
                attrAttrgroupRelationDao.insert(relation);
            }
        }
    }
    /**
     * 获取指定分组关联的所有属性
     */
    @Override
    public List<AttrEntity> getAttrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities=attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrGroupId));
        //List<AttrEntity> attrEntities = relationEntities.stream().map(item -> this.getById(item.getAttrId())).collect(Collectors.toList());
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        if(attrIds==null||attrIds.size()==0){
            return new ArrayList<>();
        }
        return this.listByIds(attrIds);
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] relations) {
        List<AttrAttrgroupRelationEntity> relationList = Arrays.asList(relations).stream().map(item -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
//            attrAttrgroupRelationEntity.setAttrId(item.getAttrId());
//            attrAttrgroupRelationEntity.setAttrGroupId(item.getAttrGroupId());
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(relationList);
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils attrNoRelation(Map<String, Object> params, Long attrGroupId) {
        //1.得到该分组的分类Id
        Long categoryId=attrGroupDao.selectById(attrGroupId).getCatelogId();
        //2.获得该分类下所有分组已关联的属性
        //2.1得到该分类下所有分组
        List<AttrGroupEntity> attrGroupsIds=attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",categoryId));
        List<Long> groupsIds=attrGroupsIds.stream().map(item-> item.getAttrGroupId()).collect(Collectors.toList());
        //2.2得到已关联的属性
        List<Long> attrRelationIds=attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",groupsIds)).stream().map(item->item.getAttrId()).collect(Collectors.toList());
        //3.查出该分类下未关联的基本属性
        QueryWrapper<AttrEntity> wrapper=new QueryWrapper<AttrEntity>().eq("catelog_id",categoryId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).notIn("attr_id",attrRelationIds);
        String key=(String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(obj->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page =this.page(new Query<AttrEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }

    /**
     * 依据id列表 查询 可检索的attr 的 id集合
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrIds(attrIds);
    }
}